<?php

   function ancestor($e,$n) {
      for ($i = 0;$i<$n;$i++) {
        //echo $i." - ".$e->tag."<br>";
        $e = $e->parent();
      }
      //echo $i." - ".$e->tag."<br>";
      return $e;
   }

   function descendent($e,$n) {
    for ($i=0;$i<$n;$i++) {
      // echo $i." - ".$e->tag."<br>";
      $e = $e->firstChild();
    }
    //echo $i." - ".$e->tag."<br>";
    return $e;
   }

   function getLastVotes($html) {
      $peliculas = array();
      foreach($html->find('.ntext') as $e) {
        $pelicula = array();
        $ids = explode("film",$e->href);
        $ids = explode(".html",$ids[1]);
        $id = $ids[0];
        $dir = substr($id, 0, 2);
        $pelicula["id"] = $id;
        $pelicula["poster"] = "http://www.filmaffinity.com/imgs/movies/full/$dir/$id.jpg";
        $p = ancestor($e,9)->nextSibling()->firstChild();
        $pelicula["voto"] = trim($p->plaintext);
        $peliculas[] = $pelicula;
      }
      return $peliculas;
   }

   function getUserData($html,$userid) {
     $datos = array();
     $anchor = "/es/userratings.php?user_id=$userid";
     $links = $html->find("a[href=$anchor]");
     $link = $links[0];
     $table = ancestor($link,6);
     $name = descendent($table,7)->plaintext;
     $infoTable = $table->firstChild()->firstChild()->nextSibling()->firstChild();
     $votos = $infoTable->firstChild()->firstChild()->firstChild()->plaintext;
     $criticas = $infoTable->firstChild()->nextSibling()->firstChild()->firstChild()->plaintext;
     $listas =$infoTable->firstChild()->nextSibling()->nextSibling()->firstChild()->firstChild()->plaintext;
     $datos["nombre"] = $name;
     $datos["votos"] = $votos;
     $datos["criticas"] = $criticas;
     $datos["listas"] = $listas;
     return $datos;
   }

include('simple_html_dom.php');

// Generamos el DOM desde la URL de los votos del usuario
$userid = "978313";
$html = file_get_html("http://www.filmaffinity.com/es/userratings.php?user_id=$userid");

$lv = getLastVotes($html,$userid);
$data = getUserData($html,$userid);

header("Content-type: image/png");

//Settings of the image
$width = 300;
$height = 50;
$text_size = 10;
$text_X = 10;
$text_Y = 10;
$text = "Moo Cows For All";

//Create the image
$my_img = imagecreate($width, $height);

//Set a background colour
$background_color = imagecolorallocate($my_img, 0, 0, 255);

//Set a text colour
$text_colour = imagecolorallocate($my_img, 0, 255, 0);

//Create some text
imagestring($my_img, $text_size, $text_X, $text_Y, $text,$text_colour);

//Output the image
imagepng($my_img);

//Destroy the image
imagedestroy($my_img);


// print_r($lv);

?>